package org.simplextensions.di;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;

import org.simplextensions.annotations.AnnotationInfo;
import org.simplextensions.annotations.DependencyLocator;
import org.simplextensions.di.annotations.Point;
import org.simplextensions.di.annotations.Registry;
import org.simplextensions.di.annotations.ServiceDependency;
import org.simplextensions.registry.IDependencyLocatorRegistry;
import org.simplextensions.registry.IExtensionRegistry;
import org.simplextensions.registry.phaselisteners.IDependencyLocator;

@DependencyLocator({ ServiceDependency.class, Registry.class, Point.class })
public class DefaultDependencyLocator implements IDependencyLocator {

	private IExtensionRegistry extensionRegistry;

	public DefaultDependencyLocator() {
	}

	public Object getAnnotatedFieldValue(Field field, AnnotationInfo annotationInfo) {
		Object result = null;
		Class<?> fieldType = field.getType();

		Annotation annotation = annotationInfo.getAnnotation();

		if (annotation instanceof ServiceDependency) {
			result = extensionRegistry.getService(fieldType);
		} else if (annotation instanceof Registry) {
			return extensionRegistry;
		} else if (annotation instanceof Point) {
			String ep_id = ((Point) annotation).value();
			if ("".equals(ep_id)) {
				result = extensionRegistry.getExtensionPoint(fieldType);
			} else {
				result = extensionRegistry.getExtensionPoint(fieldType, ep_id);
			}
		}
		return result;
	}

	public void init(IDependencyLocatorRegistry locatorRegistry) {
		extensionRegistry = locatorRegistry.getExtensionRegistry();
	}
}
